#!/usr/bin/env python3

from quick2wire.gpio import pins, In, Out, Both
from quick2wire.selector import Selector, Timer
from quick2wire.i2c import I2CMaster
from quick2wire.parts.pcf8591 import PCF8591, FOUR_SINGLE_ENDED

max_blink_rate=5.0
min_blink_rate=1.0

selector = Selector()
button = pins.pin(0, direction=In, interrupt=Both)
led = pins.pin(1, direction=Out)
timer = Timer(interval=0.5)
i2c = I2CMaster()

with selector, button, led, timer, i2c:
    adc = PCF8591(i2c, FOUR_SINGLE_ENDED)
    rate_input = adc.single_ended_input(0)
    
    def blink_interval():
        return 1 / (min_blink_rate + rate_input.value * (max_blink_rate - min_blink_rate))
    
    selector.add(button)
    selector.add(timer)

    print("ready")
    
    while True:
        selector.wait()
        
        if selector.ready == button:
            if button.value:
                led.value = 1
                timer.interval = blink_interval()
                timer.start()
            else:
                led.value = 0
                timer.stop()
        
        elif selector.ready == timer:
            timer.wait()
            led.value = not led.value
            timer.interval = blink_interval()

